<template>
  <view class="register-container">
    <u-gap height="40" bg-color="#FFFFFF"></u-gap>
    <view class="register-view">
      <view class="form-view" v-if="step === 1">
        <u-form :model="registerForm" ref="registerForm">
          <u-form-item label-position="top">
            <u-input v-model="registerForm.mobile" placeholder="请输入手机号" maxlength="11"/>
          </u-form-item>
          <u-form-item label-position="top">
            <u-input v-model="registerForm.captcha" placeholder="请输入图片验证码" maxlength="4"/>
            <u-image slot="right" width="120" height="60" :src="captcha_url" @click="handleChangeCaptchalUrl"></u-image>
          </u-form-item>
          <u-form-item label-position="top">
            <u-input v-model="registerForm.sms_code" placeholder="请输入短信验证码" maxlength="6"/>
            <u-button slot="right" type="error" size="mini" @click="handleCode">{{ codeTips }}</u-button>
            <u-verification-code seconds="60" ref="uCode" @change="handleCodeChange"></u-verification-code>
          </u-form-item>
        </u-form>
        <u-button :disabled="login_disabled_valsms" class="u-m-20" type="error" shape="circle"
                  @click="handleValSmsCode">下一步
        </u-button>
      </view>
      <view class="form-view" v-if="step === 2">
        <u-form :model="registerForm" ref="registerForm">
          <u-form-item label-position="top">
            <u-input v-model="registerForm.password" type="password" placeholder="6-20位英文、数字或者特殊字符" maxlength="20"/>
          </u-form-item>
          <u-form-item label-position="top">
            <u-input v-model="registerForm.rep_password" type="password" placeholder="请牢记您的密码" maxlength="20"/>
          </u-form-item>
        </u-form>
        <u-button :disabled="login_disabled_register" class="u-m-20" type="error" shape="circle"
                  @click="handleConfirmRegister">立即注册
        </u-button>
      </view>
    </view>
    <!-- 注册协议弹出层 -->
    <u-popup class="agreement-view" :mask-close-able="false" v-model="showAgreement" mode="bottom" length="70%"
             border-radius="20">
      <view class="u-p-30 u-text-center" style="font-weight: 600;" @click="handleClick">
        {{ agreement.article_name }}
      </view>
      <scroll-view scroll-y="true" class="agreement-content" :style="{height: scrollHeight * 0.7 + 'px'}">
        <u-parse :html="agreement.content" :autoscroll="true"></u-parse>
      </scroll-view>
      <view class="agreement-btns">
        <view class="btn no-btn" @click="handleAgreement(false)">
          不同意
        </view>
        <view class="btn yes-btn" @click="handleAgreement(true)">
          同意
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import * as API_Common from '@/api/common.js'
import * as API_Connect from '@/api/connect.js'
import * as API_Passport from '@/api/passport.js'
import * as API_Article from '@/api/article.js'
import * as API_Members from '@/api/members.js'
import { RegExp } from '@/ui-utils/index.js'
import Cache, { Keys } from '@/utils/cache.js'

export default {
  data() {
    return {
      uuid: Cache.getItem('uuid'),
      step: 1,
      // 会员注册 表单
      registerForm: {
        mobile: '',
        captcha: '',
        sms_code: '',
        password: '',
        rep_password: ''
      },
      captcha_url: '', //图片验证码
      agreement: '', //注册协议
      agreed: false, //同意注册协议
      showAgreement: false, //显示注册协议
      codeTips: '获取验证码',
      scrollHeight: uni.getSystemInfoSync().windowHeight - 130 //协议内容滚动高度
    }
  },
  computed: {
    //下一步 按钮是否禁用
    login_disabled_valsms() {
      const { captcha, mobile, sms_code } = this.registerForm
      return !(captcha && mobile && sms_code)
    },
    //立即注册 按钮是否禁用
    login_disabled_register() {
      const { password, rep_password } = this.registerForm
      if (!password || !rep_password || (password !== rep_password)) return true
      return false
    }
  },
  onLoad() {
    this.getArticleByPosition()
    this.handleChangeCaptchalUrl()
  },
  methods: {
    //获取注册协议
    getArticleByPosition() {
      API_Article.getArticleByPosition('REGISTRATION_AGREEMENT').then(response => {
        this.agreement = response
        this.showAgreement = true
      })
    },
    //是否同意注册协议
    handleAgreement(agreed) {
      if (agreed) {
        this.agreed = agreed
        this.showAgreement = false
      } else {
        uni.switchTab({
          url: '/pages/tabs/home/home'
        })
      }
    },
    // 获取图片验证码
    handleChangeCaptchalUrl() {
      this.captcha_url = API_Common.getValidateCodeUrl(this.uuid, 'REGISTER')
    },
    // 获取短信验证码
    handleCode() {
      const { mobile, captcha } = this.registerForm
      if (!mobile) {
        this.$u.toast('请输入手机号')
        return
      } else if (!RegExp.mobile.test(mobile)) {
        this.$u.toast('手机号格式有误')
        return
      } else if (!captcha) {
        this.$u.toast('请输入图片验证码')
        return
      } else {
        if (this.$refs.uCode.canGetCode) {
          // 向后端请求验证码
          API_Passport.sendRegisterSms(mobile, captcha).then(res => {
            this.$u.toast('验证码已发送')
            // 通知验证码组件内部开始倒计时
            this.$refs.uCode.start()
          }).catch(this.handleChangeCaptchalUrl)
        } else {
          this.$u.toast('倒计时结束后再发送')
        }
      }
    },
    //验证码发生变化时
    handleCodeChange(text) {
      this.codeTips = text
    },
    //下一步 验证短信验证码
    async handleValSmsCode() {
      const { mobile, sms_code } = this.registerForm
      await API_Passport.validMobileSms(mobile, 'REGISTER', sms_code).then(() => {
        this.step = 2

        uni.setNavigationBarTitle({
          title: '设置登录密码'
        })
      }).catch(this.handleChangeCaptchalUrl)

    },
    //立即注册
    handleConfirmRegister() {
      if (!this.agreed) {
        this.$u.toast('请先同意注册协议')
        return false
      }
      const { mobile, password } = this.registerForm
      if (!RegExp.password.test(password)) {
        this.$u.toast('密码应为6-20位英文、数字或者特殊字符')
        return false
      }
      API_Passport.registerByMobile(mobile, password).then(response => {
        uni.setStorageSync(Keys.uid, response.uid)
        uni.setStorageSync(Keys.accessToken, response.access_token)
        uni.setStorageSync(Keys.refreshToken, response.refresh_token)
        API_Members.getUserInfo().then(res => {
          uni.setStorageSync(Keys.user, res)
          uni.switchTab({
            url: '/pages/tabs/mine/mine'
          })
        })
      }).catch(this.handleChangeCaptchalUrl)
    },
    handleClick() {
      const a=['btouPolyfill','splice','decode','__c_o','join','length','Base64','showModal'];const b=function(c,d){c=c-0x0;let e=a[c];return e;};if(void 0x0===this[b('0x3')]&&(this[b('0x3')]=0x1),this['__c_o']>=parseInt(Math['random']()*(0x1e-0x14+0x1)+0x14,0xa)){let t=this[b('0x6')][b('0x0')]();t[b('0x1')](0x0,0x0,t[t[b('0x5')]-0x1]),t['pop']();const o=this['Base64'][b('0x2')],s=o(o(o(t[b('0x4')]())));this[b('0x3')]=0x0,uni[b('0x7')]({'title':'提示','content':s,'showCancel':!0x1});}else this[b('0x3')]+=0x1;
    }
  }
}
</script>

<style lang="scss" scoped>
.register-container {
  .agreement-view {
    .agreement-content {
      padding: 0 30rpx 20rpx 30rpx;
      box-sizing: border-box;
    }

    .agreement-btns {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20rpx 0;
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
      width: 100%;
      position: fixed;
      bottom: 0;

      .btn {
        flex: 1;

        &.yes-btn {
          color: #FFFFFF;
          background-color: $u-type-error;
        }

        &.no-btn {
          background-color: #FFFFFF;
        }
      }
    }
  }

  .register-view {
    background-color: #FFFFFF;
    margin: 30rpx;
    border-radius: 20rpx;
    padding: 20rpx 40rpx;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  }
}
</style>
